package br.com.localfloripa.dao;

import java.util.List;

import javax.inject.Named;
import javax.persistence.Query;

import br.com.localfloripa.entities.Cliente;

@Named("clienteDao")
public class ClienteDao extends DaoManager<Cliente> {

	
	public Cliente findById(Long idCliente) throws Exception {
		return em.find(Cliente.class, idCliente);
	}
	
	public Cliente findByURLTemplate(String urlTemplate) throws Exception {
		
		Query query = em.createQuery("SELECT c FROM Cliente c WHERE c.template.url = :urlTemplate");
		query.setParameter("urlTemplate", urlTemplate);
		
		return (Cliente) query.getSingleResult();
	}
	
	public List<Cliente> listClientesPaginada(int first,int pageSize) throws Exception {
		
		Query query = em.createQuery("SELECT c FROM Cliente c ORDER BY c.pessoa.nome");
		query.setFirstResult(first);
		query.setMaxResults(pageSize);		
		return query.getResultList();
	}
	
	public Long countListClientes() {
		Query query = em.createQuery("SELECT COUNT(c.id) FROM Cliente c");
		return (Long) query.getSingleResult();
	}

	public List<Cliente> listClientesOrdemNome() throws Exception {
		Query query = em.createQuery("SELECT new Cliente(c.id,c.pessoa) FROM Cliente c WHERE c.ativo IS TRUE ORDER BY c.pessoa.nome");
		return query.getResultList();
	}
	
	public List<Cliente> listClientesProprietarios() throws Exception {
		
		Query query = em.createQuery("SELECT new Cliente(c.id,c.pessoa) FROM Cliente c WHERE c.ativo IS TRUE AND c.id NOT IN (SELECT r.id FROM Representante r) ORDER BY c.pessoa.nome");
		return query.getResultList();		
	}
	
	
}
